import { reactive, toRefs, computed } from "vue"
import { onShow, onUnload, onReady, onLoad } from "@dcloudio/uni-app";
import { LoginStore } from "@/store/modules/login";
import md5 from "js-md5"
import { Base64 } from "js-base64"
const mediaAdApi = uniCloud.importObject('media-ad', { customUI: true })
// #ifdef APP
// 语音红包SDK
const voicdeReadSdk = uni.requireNativePlugin('xlx-voice-read-module');
// 蘑菇星球SDK
const mokuHelper = uni.requireNativePlugin('moku-sdk');
// #endif
/**
 * @description  媒体任务接入
 * @param
 * */
export const usePlugin = () => {
	const LoginState = LoginStore()
	// 获取用户信息
	const userInfo = computed(() => (LoginState.userInfo))
	const state = reactive({
		data: [],
		preEcpm: 0, //语音红包千次展示预估收益
		wv: "", //当前页面的webview对象
		url: '', //跳转页面
		name: '', //判断是进入的那个媒体
		oaid: "" //设备oaid
	})
	onLoad(async (e) => {
		console.log(e);
		state.name = e.name
		// 初始化对应的媒体
		await init()
		// #ifdef APP
		if (JSON.stringify(e) == '{}') {
			const yyhb = findObjectByName(state.data, '语音红包')
			//初始化语音红包
			voicdeReadSdk.init({
				appId: yyhb.mediaID, //渠道appId，从配置后台获取
				appSecret: yyhb.Secretkey, //密钥，从配置后台获取
				debug: false
			});
			// 初始化蘑菇星球
			mokuHelper.onLoad();
			mokuHelper.requestPermissions();
		}
		// #endif

	})

	// 等待页面加载完成后，在渲染对应的媒体游戏画面
	onReady(() => {
		if (state.name !== '语音红包' && state.name !== '蘑菇星球') {
			openMedia()
		}
	})
	onShow(() => {
		if (state.name == '蘑菇星球') {
			mokuHelper.onShow();
		}
	})
	onUnload(() => {
		if (state.name == '蘑菇星球') {
			mokuHelper.onUnload();
		}
	})
	/***
	 * @description: 找出对应的媒体
	 * @param {*}
	 * @return {*}
	 * @author: white_queen
	 */
	const findObjectByName = (array, name) => {
		// 使用 Array.find 方法查找数组中符合条件的对象
		return array.find(obj => obj.name === name);
	}
	// 初始化媒体接口
	const init = async () => {
		const res = await mediaAdApi.getmediaList({ pageNum: 1, pageSize: 20 })
		state.data = res.data
		switch (state.name) {
			case "多量试玩":
				const dl = findObjectByName(res.data, '多量试玩')
				getDeviceInfo(dl, state.name)
				break;
			case "淘金试玩":
				const tj = findObjectByName(res.data, '淘金试玩')
				getDeviceInfo(tj, state.name)
				break;
			case "点赚试玩":
				const dz = findObjectByName(res.data, '点赚试玩')
				getDeviceInfo(dz, state.name)
				break;
			case "闪电盒子":
				const { mediaID, Secretkey } = findObjectByName(res.data, '闪电盒子')
				let sd = mediaID + '-' + Secretkey + ':sdkUserId=' + userInfo?.value?._id + '&'
				state.sign = md5(sd).toUpperCase();
				state.url =
					`https://sdkh5.gouzixsw.com/#/?channelId=${mediaID}&userId=${userInfo?.value?._id}&sign=${state.sign}`
				break;
		}
	}


	// 展示媒体（注意，因为语音红包-蘑菇星球 需要手动点击操作，所以要导出该方法，进行点击操作）
	const openMedia = (code) => {
		var pages = getCurrentPages();
		var page = pages[pages.length - 1];
		// #ifdef APP-PLUS
		var currentWebview = page.$getAppWebview();
		console.log(currentWebview.id); //获得当前webview的id
		console.log(currentWebview.isVisible()); //查询当前webview是否可见
		// #endif
		const name = state.name || code
		switch (name) {
			case "多量试玩":
				setTimeout(() => {
					state.wv = currentWebview.children()[0]
					state.wv.appendJsFile('_www/hybrid/html/duoliang.js');
				}, 1000)
				break;
			case "淘金试玩":
				setTimeout(() => {
					state.wv = currentWebview.children()[0]
					state.wv.appendJsFile('_www/hybrid/html/taojin-app.js');
				}, 1000)
				break;
			case "点赚试玩":
				setTimeout(() => {
					state.wv = currentWebview.children()[0]
					state.wv.appendJsFile('_www/hybrid/html/dianzhuan.js');
				}, 1000)
				break;
			case "语音红包":
				const { mediaID } = findObjectByName(state.data, '语音红包')
				// 预加载广告
				voicdeReadSdk.loadVoiceAd({
					resourceId: '1913515819', //必要，资源位id
					userId: userInfo?.value?._id, //可选，用于服务端回调时通知接入方给哪个用户发放奖励，不走服务端回调非必要
					mediaExtra: { content: "语音红包奖励", mediaid: mediaID }, //可选，额外的透传参数，仅支持单个json对象格式，不可以嵌套json对象
					nickname: userInfo?.value?.nickname //可选，用户昵称
				}, result => {
					console.log("result = " + JSON.stringify(result));
					switch (result.eventType) {
						//广告加载成功(注：此时只是广告加载成功，并没有展示。如需直接展示还需调用 showVoiceAd 方法)
						case "onAdLoadSuccess":
							// preEcpm 千次展现预估收益，单次展现收益需要除1000
							state.preEcpm = result.params.preEcpm;
							// 展示广告
							voicdeReadSdk.showVoiceAd(result => {
								console.log("result = " + JSON.stringify(result));
								switch (result.eventType) {
									case "onAdShow":
										console.log('展示了');
										//语音展示完成
										break;
									case "onAdError":
										var errorCode = result.params.errorCode;
										//广告展示失败
										break;
									case "onAdClose":
										console.log('关闭了');
										//广告关闭
										break;
										/**
										 * 奖励验证回调，开发者需要在此回调中做奖励的发放
										 * 多个奖励则会回调多次
										 */
									case "onRewardVerify":
										//requestId 当前曝光的请求id
										var requestId = result.params.requestId;
										// tagId 奖励唯一标识
										var tagId = result.params.tagId;
										//rewardAmount 当次广告媒体收益（单位元）
										var rewardAmount = result.params.rewardAmount;
										console.log('本次广告收益', rewardAmount);
										break;
								}
							})
							break;
							// 广告加载失败
						case "onAdLoadError":
							var errorCode = result.params.errorCode;
							var errorMsg = result.params.errorMsg;
							//请务必给用户展示错误信息，方便用户反馈时排查问题
							uni.showToast({
								icon: 'none',
								title: `${errorMsg}(${errorCode})`,
								duration: 2000
							});
							break;
					}
				})
				break;
			case "蘑菇星球":
				const mg = findObjectByName(state.data, '蘑菇星球')
				getDeviceInfo(mg, name)
				break
		}
	}


	// 获取设备OAID，并进行sign签名后返回对应的url，使用web-view 进行渲染
	const getDeviceInfo = (data, name) => {
		const { mediaID, Secretkey } = data
		//Android OAID获取方法介绍
		var Build = plus.android.importClass("android.os.Build");
		var androidosv = Build.VERSION.SDK_INT;
		console.log(androidosv);
		const info = uni.getSystemInfoSync();
		if (androidosv >= 29) {
			plus.device.getOAID({
				success: (e) => {
					state.oaid = e.oaid
					// console.log('getOAID success: ' + JSON.stringify(e));
					switch (name) {
						case "多量试玩":
							let device_ids = JSON.stringify({ "7": e.oaid })
							let hehe = encodeURIComponent(device_ids)
							let oo =
								`device_ids=${hehe}&device_type=2&media_id=${mediaID}&user_id=${userInfo?.value?._id}&key=${Secretkey}`
							state.sign = md5(oo)
							state.url =
								`https://h5.ads66.com/?media_id=${mediaID}&user_id=${userInfo?.value?._id}&device_ids=${hehe}&device_type=2&sign=${state.sign}`
							break;
						case "淘金试玩":
							let qm =
								`${info.model}#${userInfo?.value?._id}#${mediaID}#${e.oaid}#${androidosv}#${Secretkey}`
							state.sign = md5(Base64.encode(qm))
							state.url =
								`https://app.91taojin.com.cn/?MtId=${mediaID}&MtIDUser=${userInfo?.value?._id}&MobileModel=${info.model}&SysVer=${androidosv}&OAID=${e.oaid}&sign=${state.sign}`
							break;
						case "点赚试玩":
							console.log(userInfo?.value?.mobile)
							// 获取当前时间的时间戳（秒）
							const timestamp = Math.floor(new Date().getTime() / 1000);
							let dd = mediaID + userInfo?.value?.my_invite_code + e.oaid + timestamp + Secretkey
							state.sign = md5(dd)
							state.url =
								`http://dy.down5g.com/list?timestamp=${timestamp}&type=1&app_id=${mediaID}&userid=${userInfo?.value?.my_invite_code}&deviceid=${e.oaid}&imeis=${androidosv}&sign=${state.sign}`
							break;
						case "蘑菇星球":
							//配置用户id(必传)
							mokuHelper.putStringMokuOption("userId", userInfo?.value?._id);
							//配置appId(必传)
							mokuHelper.putStringMokuOption("appId", mediaID);
							//配置appSecret(必传)
							mokuHelper.putStringMokuOption("appSecret", Secretkey);
							//配置oaid(必传)
							mokuHelper.putStringMokuOption("oaid", e.oaid);
							//配置imei(必传)
							mokuHelper.putStringMokuOption("imei", e.oaid);
							//配置对接方式(必传) -1:兼容老版本sdk对接 0:sdk对接 1:cpa弹窗对接 2:api对接
							mokuHelper.putIntegerMokuOption("cutInType", 0);

							mokuHelper.putStringMokuOption("titleText", "蘑菇星球");
							mokuHelper.startSdk();
							break;
					}
				},
				fail: function(e) {
					console.log('getOAID failed: ' + JSON.stringify(e));
					console.log(e.oaid);
				}
			});
		} else {
			//Android IMEI获取方法介绍
			plus.device.getInfo({
				success: function(e) {
					let imei1 = e.imei.split(',')[0] || ''
					let imei2 = e.imei.split(',')[1] || ''
					let imsi = e.imsi[0] || ''
					switch (name) {
						case "多量试玩":
							let device_ids = JSON.stringify({ "1": imei1, '2': imei2, })
							let hehe = encodeURIComponent(device_ids)
							let oo =
								`device_ids=${hehe}&device_type=2&media_id=${mediaID}&user_id=${userInfo?.value?._id}&key=${Secretkey}`
							state.sign = md5(oo)
							state.url =
								`https://h5.ads66.com/?media_id=${mediaID}&user_id=${userInfo?.value?._id}&device_ids=${hehe}&device_type=2&sign=${state.sign}`
							break;
						case "淘金试玩":
							let qm =
								`${imei1}#${info.model}#${userInfo?.value?._id}#${mediaID}#${androidosv}#${Secretkey}`
							state.sign = md5(Base64.encode(qm))
							state.url =
								`https://app.91taojin.com.cn/?MtId=${mediaID}&MtIDUser=${userInfo?.value?._id}&IMEI=${imei1}&MobileModel=${info.model}&SysVer=${androidosv}&sign=${state.sign}`
							break;
						case "点赚试玩":
							// 获取当前时间的时间戳（秒）
							const timestamp = Math.floor(new Date().getTime() / 1000);
							let dd = mediaID + userInfo?.value?._id + imei1 + timestamp + Secretkey
							state.sign = md5(dd)
							state.url =
								`http://dy.down5g.com/list?timestamp=${timestamp}&type=1&app_id=${mediaID}&userid=${userInfo?.value?._id}&deviceid=${imei1}&imeis=${imei1,imei2,androidosv}&sign=${state.sign}`
							break;
						case "蘑菇星球":
							plus.device.getOAID({
								success: (e) => {
									state.oaid = e.oaid
									//配置用户id(必传)
									mokuHelper.putStringMokuOption("userId", userInfo?.value?._id);
									//配置appId(必传)
									mokuHelper.putStringMokuOption("appId", mediaID);
									//配置appSecret(必传)
									mokuHelper.putStringMokuOption("appSecret", Secretkey);
									//配置oaid(必传)
									mokuHelper.putStringMokuOption("oaid", e.oaid);
									//配置imei(必传)
									mokuHelper.putStringMokuOption("imei", imei1);
									//配置对接方式(必传) -1:兼容老版本sdk对接 0:sdk对接 1:cpa弹窗对接 2:api对接
									mokuHelper.putIntegerMokuOption("cutInType", 0);

									mokuHelper.putStringMokuOption("titleText", "蘑菇星球");
									mokuHelper.startSdk();
								}
							})
							break;
					}
					console.log('getDeviceInfo success: ' + JSON.stringify(e));
				},
				fail: function(e) {
					console.log('getDeviceInfo failed: ' + JSON.stringify(e));
				}
			});
		}
	}


	return {
		...toRefs(state),
		openMedia
	};

};